package cn.client.ui.view.signIn

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.data.UserStateManager
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.User
import cn.client.data.remoteData.bean.VerifyAccount
import cn.client.data.localData.dao.UserDao
import cn.client.data.localData.entity.UserEntity
import cn.client.data.remoteData.bean.LoginRes
import cn.client.data.remoteData.repository.SignInRepository
import cn.client.data.userStateManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


/**
 * 登录ViewModel
 */
@HiltViewModel
class SignInViewModel @Inject constructor(
    private val repository: SignInRepository,
    private val userDao: UserDao
) : ViewModel() {

    /**
     * 事件管道
     */
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    /**
     * 可观察事件数据流
     */
    val pageEvents = _pageEvents.receiveAsFlow()

    // 可变状态
    var pageStates by mutableStateOf(PageState())
        private set

    // 使用MutableStateFlow来存储用户列表
    private val _userEntity = MutableStateFlow<UserEntity?>(null)
    val userEntity: StateFlow<UserEntity?> = _userEntity


    /**
     * 收集意图
     */
    fun dispatch(intent: PageIntent){
        when(intent) {
            is PageIntent.VerifyAccount -> verifyAccount(intent.account)
            is PageIntent.VerifyPwd -> verifyPwd(intent.account, intent.password)
            is PageIntent.SelectUser -> selectUser(intent.any)
            else -> {Unit}
        }
    }

    // 处理意图：发送验证账号网络请求
    private fun verifyAccount(account: String){
        pageStates = pageStates.copy(account = account)
        Log.d("处理意图","输入的账号为：${pageStates.account}")
        // TODO: send to request for network
        viewModelScope.launch {
            try {
                val res = repository.signInAccount(VerifyAccount(account))
                pageStates = pageStates.copy(verifyStatus = res.msg)
                if (res.code == 200){
                    _pageEvents.send(PageEvent.Result(res))
                } else {
                    _pageEvents.send(PageEvent.Error("账户 $account 不存在，返回信息：${res.msg}"))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("error","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图：发送验证密码网络请求
    private fun verifyPwd(account:String, password: String){
        pageStates = pageStates.copy(account=account, password = password)
        Log.d("处理意图","登录的账号为：$account")
        val user: User = User(account = account, password = password)
        viewModelScope.launch {
            try {
                val res = repository.signInSecond(user)
                Log.d("登录响应","响应信息：${res.msg}")
                if (res.code == 200){
                    // 缓存用户id
                    val thisUid = res.data?.uid
                    Log.d("SignInViewModel","缓存用户id：$thisUid")
                    val primaryId = userDao.insert(UserEntity(uid = res.data!!.uid))
                    if (primaryId != null){
                        if (thisUid != null){
                            // 修改全局状态
                            userStateManager.setUserId(newId = thisUid)
                        }
                        _pageEvents.send(PageEvent.LoginRes(res))
                    } else {
                        _pageEvents.send(PageEvent.Error("缓存失败"))
                    }
                } else {
                    _pageEvents.send(PageEvent.Error("密码错误，返回信息：${res.msg}"))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("error","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    private fun selectUser(any: Any){
        viewModelScope.launch {
            userDao.getUser().catch { e ->
                Log.d("MainViewModel", "错误：$e")
            }.collect { it ->
                _userEntity.value = it
            }
        }
    }

    /**
     * 意图集
     */
    sealed class PageIntent {
        data class VerifyAccount(val account: String): PageIntent()
        data class VerifyPwd(val account: String, val password: String):PageIntent()
        data class SelectUser(val any: Any) : PageIntent()

    }

    /**
     * 事件集
     */
    sealed class PageEvent {
        object Idle :PageEvent() // 空闲
        object Loading : PageEvent()  // 加载
        data class Result(val result: BaseResp<Any>) : PageEvent()     // 响应1
        data class LoginRes(val loginRes: BaseResp<cn.client.data.remoteData.bean.LoginRes>) : PageEvent()     // 响应2
        data class Error(val error: String) : PageEvent()   // 错误信息
    }


    /**
     * 状态集
     */
    data class PageState(
        val account: String = "",
        val password: String = "",
        // 验证状态
        val verifyStatus: String = "",
    )
}